class Bill < ActiveRecord::Base
  attr_accessible :sold_date, :customer_id, :electrician_id,:ref_id,:total_commission,:tax_total,:grand_total
  validates :customer_id, :presence => true
  validates :electrician_id, :presence => true
  validates :sold_date, :presence => true
  validates :ref_id, :presence => true


  def recompute_totals()
    all_solds = solds()
    update_attribute(:total_commission,all_solds.reduce(0){|total,sold| total+sold.commission})
    update_attribute(:total_tax,all_solds.reduce(0){|total,sold| total+sold.tax})
    update_attribute(:grand_total, all_solds.reduce(0){|total,sold| total+sold.total}+total_tax)
  end

  def solds()
    Sold.find_all_by_ref_id(ref_id)
  end

  def self.delete_all_sold_items_from_bill(ref_id)
    Sold.find_all_by_ref_id(ref_id).each do |sold|
      @stock = Stock.find(sold.stock_id)
      @stock.quantity = @stock.quantity + sold.quantity
      @stock.save
      sold.destroy
    end
  end

end
